﻿using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using GtsServer.Common;

namespace GtsServer.DAL
{
    /// <summary>
    /// 数据访问类:[User]
    /// </summary>
    public partial class UserDAL
    {
        public UserDAL()
        { }
        #region  Method

        /// <summary>
        /// 得到最大ID
        /// </summary>
        public int GetMaxId()
        {
            return DbHelperSQL.GetMaxID("ID", "[User]");
        }

        public bool ExistByIMSIAndMacAddr(string addr)
        {
            string sql = " select count(1) from [User] where IMSI+Mac = '" + addr + "'";
            return DbHelperSQL.Exists(sql);
        }

        public DataSet RegisterUser(string userAccount, string account, string pwd)
        {
            IDataParameter[] parms = new IDataParameter[]{ 
                new SqlParameter("@userAccount",userAccount),
                new SqlParameter("@account",account),
                new SqlParameter("@pwd",pwd)
            };
            DataSet ds = DbHelperSQL.RunProcedure("RegisterUser", parms, "RegisterUser");
            return ds;
        }

        /// <summary>
        /// 推荐信息
        /// </summary>
        public DataSet GetModelByUserAccount(string userAccount)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * ");
            strSql.Append(" FROM [User] where useraccount ='" + userAccount + "'");
            return DbHelperSQL.Query(strSql.ToString());
        }

        /// <summary>
        /// 验证推荐码
        /// </summary>
        public DataSet InviteVerif(string userAccount, string inviteAccount)
        {
            IDataParameter[] parms = new IDataParameter[]{ 
                new SqlParameter("@userAccount",userAccount),
                new SqlParameter("@inviteAccount",inviteAccount)
            };
            DataSet ds = DbHelperSQL.RunProcedure("InviteVerif", parms, "InviteVerif");
            return ds;
        }

        /// <summary>
        /// 推荐提取金币
        /// </summary>
        public DataSet InviteGetCoin(string userAccount)
        {
            IDataParameter[] parms = new IDataParameter[]{ 
                new SqlParameter("@userAccount",userAccount)
            };
            DataSet ds = DbHelperSQL.RunProcedure("InviteGetCoin", parms, "InviteGetCoin");
            return ds;
        }


        public DataSet LoginUser(string userAccount, string account, string pwd)
        {
            IDataParameter[] parms = new IDataParameter[]{ 
                new SqlParameter("@userAccount",userAccount),
                new SqlParameter("@account",account),
                new SqlParameter("@pwd",pwd)
            };
            DataSet ds = DbHelperSQL.RunProcedure("UserLogin", parms, "LoginUser");
            return ds;
        }

        public DataSet EditUserName(int userInfoID, string userName)
        {
            IDataParameter[] parms = new IDataParameter[]{ 
                new SqlParameter("@userInfoID",userInfoID),
                new SqlParameter("@userName",userName)
            };
            DataSet ds = DbHelperSQL.RunProcedure("EditUserName", parms, "EditUserName");
            return ds;
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(int ID)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from [User]");
            strSql.Append(" where ID=@ID");
            SqlParameter[] parameters = {
					new SqlParameter("@ID", SqlDbType.Int,4)
};
            parameters[0].Value = ID;

            return DbHelperSQL.Exists(strSql.ToString(), parameters);
        }

        private string imei;
        private string number;
        private string area;
        private string plmn;
        private string mac;
        private string userAccount;
        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(GtsServer.Model.User model)
        {
            StringBuilder strSql = new StringBuilder();
            IDataParameter[] parameters = {
					new SqlParameter("@CommunicationID", SqlDbType.Int,4),
					new SqlParameter("@IsRobot", SqlDbType.Bit,1),
					new SqlParameter("@State", SqlDbType.Int,4),
					new SqlParameter("@RegisterTime", SqlDbType.DateTime),
					new SqlParameter("@UserInfoID", SqlDbType.Int,4),
					new SqlParameter("@ChanceTypeID", SqlDbType.Int,4),
					new SqlParameter("@PLSettingID", SqlDbType.Int,4),
					new SqlParameter("@IMSI", SqlDbType.VarChar,30),
					new SqlParameter("@imei", SqlDbType.VarChar,30),
					new SqlParameter("@number", SqlDbType.VarChar,20),
					new SqlParameter("@area", SqlDbType.VarChar,20),
					new SqlParameter("@plmn", SqlDbType.VarChar,10),
					new SqlParameter("@mac", SqlDbType.VarChar,50),
					new SqlParameter("@userAccount", SqlDbType.VarChar,10)};
            parameters[0].Value = model.CommunicationID;
            parameters[1].Value = model.IsRobot;
            parameters[2].Value = model.State;
            parameters[3].Value = model.RegisterTime;
            parameters[4].Value = model.UserInfoID;
            parameters[5].Value = model.ChanceTypeID;
            parameters[6].Value = model.PLSettingID;
            parameters[7].Value = model.IMSI ?? "";
            parameters[8].Value = model.IMEI ?? "";
            parameters[9].Value = model.Number ?? "";
            parameters[10].Value = model.Area ?? "";
            parameters[11].Value = model.Plmn ?? "";
            parameters[12].Value = model.Mac ?? "";
            parameters[13].Value = model.UserAccount ?? "";

            DataSet ds = DbHelperSQL.RunProcedure("AddUser", parameters, "User");
            if (ds == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            }
        }

        /// <summary>
        /// 获取水果机1.0的用户数据
        /// </summary>
        /// <param name="imsi"></param>
        /// <param name="imei"></param>
        /// <param name="mac"></param>
        /// <returns></returns>
        public DataSet CheckFirstFruitUser(string imsi, string imei, string mac)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("declare @imsi varchar(50),@imei varchar(50),@mac varchar(50),@goldNum int,@eggNum int,@name varchar(50),@pwd varchar(50),@isExist int ");
            strSql.Append("set @imsi = '" + imsi + "';");
            strSql.Append("set @imei='" + imei + "';");
            strSql.Append("set @mac = '" + mac + "';");
            strSql.Append("set @isExist =1;");
            strSql.Append("if((select count(1) from SNSMember where imsi=@imsi)>0) select @goldNum = GoldNum,@eggNum =EggNum,@name=Account,@pwd=Password from SNSMember where imsi=@imsi;");
            strSql.Append("else if((select count(1) from SNSMember where imsi=@imei)>0) select @goldNum = GoldNum,@eggNum =EggNum,@name=Account,@pwd=Password from SNSMember where imsi=@imei;");
            strSql.Append("else if ((select count(1) from SNSMember where imsi=@imsi+'_'+@mac)>0) select @goldNum = GoldNum,@eggNum =EggNum,@name=Account,@pwd=Password from SNSMember where imsi=@imsi+'_'+@mac;");
            strSql.Append("else if((select count(1) from SNSMember where imsi=@imei+'_'+@mac)>0) select @goldNum = GoldNum,@eggNum =EggNum,@name=Account,@pwd=Password from SNSMember where imsi=@imei+'_'+@mac;");
            strSql.Append("else if((select count(1) from SNSIMSI where imsi=@imsi)>0) select @goldNum = GoldNum,@eggNum =EggNum,@name=Account,@pwd='' from SNSIMSI where imsi=@imsi;");
            strSql.Append("else if((select count(1) from SNSIMSI where imsi=@imei)>0) select @goldNum = GoldNum,@eggNum =EggNum,@name=Account,@pwd='' from SNSIMSI where imsi=@imei;");
            strSql.Append("else if ((select count(1) from SNSIMSI where imsi=@imsi+'_'+@mac)>0) select @goldNum = GoldNum,@eggNum =EggNum,@name=Account,@pwd='' from SNSIMSI where imsi=@imsi+'_'+@mac;");
            strSql.Append("else if((select count(1) from SNSIMSI where imsi=@imei+'_'+@mac)>0) select @goldNum = GoldNum,@eggNum =EggNum,@name=Account,@pwd='' from SNSIMSI where imsi=@imei+'_'+@mac;");
            strSql.Append("else set @isExist =0;");
            strSql.Append("select @name name,@pwd pwd,@goldNum goldNum,@eggNum eggNum,@isExist isExist");

            return DbHelperSQL.Query(strSql.ToString(), ConnectionEnum.ConnectionFirst);
        }

        /// <summary>
        /// 将1.0数据库中的用户金币及菜单数量更新至2.0库中
        /// </summary>
        /// <param name="userAccount"></param>
        /// <param name="name"></param>
        /// <param name="pwd"></param>
        /// <param name="goldNum"></param>
        /// <param name="eggNum"></param>
        public void EditFirstUserInitData(string userAccount, string name, string pwd, int goldNum, int eggNum)
        {
            IDataParameter[] parms = new IDataParameter[]{ 
                new SqlParameter("@userAccount",userAccount),
                new SqlParameter("@name",name),
                new SqlParameter("@pwd",pwd),
                new SqlParameter("@goldNum",goldNum),
                new SqlParameter("@eggNum",eggNum)
            };
            DbHelperSQL.RunProcedure("EditUserInitData", parms, "EditUserInitData");
        }

        public DataSet CheckUser(GtsServer.Model.User model)
        {
            StringBuilder strSql = new StringBuilder();
            IDataParameter[] parameters = {
					new SqlParameter("@CommunicationID", SqlDbType.Int,4),
					new SqlParameter("@IsRobot", SqlDbType.Bit,1),
					new SqlParameter("@State", SqlDbType.Int,4),
					new SqlParameter("@RegisterTime", SqlDbType.DateTime),
					new SqlParameter("@UserInfoID", SqlDbType.Int,4),
					new SqlParameter("@ChanceTypeID", SqlDbType.Int,4),
					new SqlParameter("@PLSettingID", SqlDbType.Int,4),
					new SqlParameter("@IMSI", SqlDbType.VarChar,30),
					new SqlParameter("@imei", SqlDbType.VarChar,30),
					new SqlParameter("@number", SqlDbType.VarChar,20),
					new SqlParameter("@area", SqlDbType.VarChar,20),
					new SqlParameter("@plmn", SqlDbType.VarChar,10),
					new SqlParameter("@mac", SqlDbType.VarChar,50),
					new SqlParameter("@userAccount", SqlDbType.VarChar,10)};
            parameters[0].Value = model.CommunicationID;
            parameters[1].Value = model.IsRobot;
            parameters[2].Value = model.State;
            parameters[3].Value = model.RegisterTime;
            parameters[4].Value = model.UserInfoID;
            parameters[5].Value = model.ChanceTypeID;
            parameters[6].Value = model.PLSettingID;
            parameters[7].Value = model.IMSI;
            parameters[8].Value = model.IMEI;
            parameters[9].Value = model.Number;
            parameters[10].Value = model.Area;
            parameters[11].Value = model.Plmn;
            parameters[12].Value = model.Mac;
            parameters[13].Value = model.UserAccount;

            DataSet ds = DbHelperSQL.RunProcedure("CheckUser", parameters, "CheckUser");
            return ds;
        }


        public bool UpdateRequestTime(DateTime dt, string addr)
        {
            string sql = "update [user] set PrevRequestTime='" + dt + "' where  IMSI+Mac='" + addr + "'";
            try
            {
                DbHelperSQL.ExecuteSql(sql);
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                return false;
            }
        }
        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(GtsServer.Model.User model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update [User] set ");
            //strSql.Append("CommunicationID=@CommunicationID,");
            //strSql.Append("IsRobot=@IsRobot,");
            strSql.Append("State=@State");
            //strSql.Append("RegisterTime=@RegisterTime,");
            //strSql.Append("UserInfoID=@UserInfoID,");
            //strSql.Append("ChanceTypeID=@ChanceTypeID,");
            //strSql.Append("PLSettingID=@PLSettingID,");
            //strSql.Append("IMSI=@IMSI");
            strSql.Append(" where ID=@ID");
            SqlParameter[] parameters = {
					//new SqlParameter("@CommunicationID", SqlDbType.Int,4),
                    //new SqlParameter("@IsRobot", SqlDbType.Bit,1),
					new SqlParameter("@State", SqlDbType.Int,4),
                    //new SqlParameter("@RegisterTime", SqlDbType.Date,3),
					//new SqlParameter("@UserInfoID", SqlDbType.Int,4),
					//new SqlParameter("@ChanceTypeID", SqlDbType.Int,4),
					//new SqlParameter("@PLSettingID", SqlDbType.Int,4),
					//new SqlParameter("@IMSI", SqlDbType.VarChar,30),
					new SqlParameter("@ID", SqlDbType.Int,4)};
            //parameters[0].Value = model.CommunicationID;
            //parameters[1].Value = model.IsRobot;
            parameters[0].Value = model.State;
            //parameters[3].Value = model.RegisterTime;
            //parameters[2].Value = model.UserInfoID;
            //parameters[3].Value = model.ChanceTypeID;
            //parameters[4].Value = model.PLSettingID;
            //parameters[5].Value = model.IMSI;
            parameters[1].Value = model.ID;

            int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int ID)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from [User] ");
            strSql.Append(" where ID=@ID");
            SqlParameter[] parameters = {
					new SqlParameter("@ID", SqlDbType.Int,4)
};
            parameters[0].Value = ID;

            int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 批量删除数据
        /// </summary>
        public bool DeleteList(string IDlist)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from [User] ");
            strSql.Append(" where ID in (" + IDlist + ")  ");
            int rows = DbHelperSQL.ExecuteSql(strSql.ToString());
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public GtsServer.Model.User GetModel(int ID)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select  top 1 ID,CommunicationID,IsRobot,State,RegisterTime,UserInfoID,ChanceTypeID,PLSettingID,IMSI from [User] ");
            strSql.Append(" where ID=@ID");
            SqlParameter[] parameters = {
					new SqlParameter("@ID", SqlDbType.Int,4)
};
            parameters[0].Value = ID;

            GtsServer.Model.User model = new GtsServer.Model.User();
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                if (ds.Tables[0].Rows[0]["ID"] != null && ds.Tables[0].Rows[0]["ID"].ToString() != "")
                {
                    model.ID = int.Parse(ds.Tables[0].Rows[0]["ID"].ToString());
                }
                if (ds.Tables[0].Rows[0]["CommunicationID"] != null && ds.Tables[0].Rows[0]["CommunicationID"].ToString() != "")
                {
                    model.CommunicationID = int.Parse(ds.Tables[0].Rows[0]["CommunicationID"].ToString());
                }
                if (ds.Tables[0].Rows[0]["IsRobot"] != null && ds.Tables[0].Rows[0]["IsRobot"].ToString() != "")
                {
                    if ((ds.Tables[0].Rows[0]["IsRobot"].ToString() == "1") || (ds.Tables[0].Rows[0]["IsRobot"].ToString().ToLower() == "true"))
                    {
                        model.IsRobot = true;
                    }
                    else
                    {
                        model.IsRobot = false;
                    }
                }
                if (ds.Tables[0].Rows[0]["State"] != null && ds.Tables[0].Rows[0]["State"].ToString() != "")
                {
                    model.State = int.Parse(ds.Tables[0].Rows[0]["State"].ToString());
                }
                if (ds.Tables[0].Rows[0]["RegisterTime"] != null && ds.Tables[0].Rows[0]["RegisterTime"].ToString() != "")
                {
                    model.RegisterTime = DateTime.Parse(ds.Tables[0].Rows[0]["RegisterTime"].ToString());
                }
                if (ds.Tables[0].Rows[0]["UserInfoID"] != null && ds.Tables[0].Rows[0]["UserInfoID"].ToString() != "")
                {
                    model.UserInfoID = int.Parse(ds.Tables[0].Rows[0]["UserInfoID"].ToString());
                }
                if (ds.Tables[0].Rows[0]["ChanceTypeID"] != null && ds.Tables[0].Rows[0]["ChanceTypeID"].ToString() != "")
                {
                    model.ChanceTypeID = int.Parse(ds.Tables[0].Rows[0]["ChanceTypeID"].ToString());
                }
                if (ds.Tables[0].Rows[0]["PLSettingID"] != null && ds.Tables[0].Rows[0]["PLSettingID"].ToString() != "")
                {
                    model.PLSettingID = int.Parse(ds.Tables[0].Rows[0]["PLSettingID"].ToString());
                }
                if (ds.Tables[0].Rows[0]["IMSI"] != null && ds.Tables[0].Rows[0]["IMSI"].ToString() != "")
                {
                    model.IMSI = ds.Tables[0].Rows[0]["IMSI"].ToString();
                }
                return model;
            }
            else
            {
                return null;
            }
        }

        


        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetList(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select ID,CommunicationID,IsRobot,State,RegisterTime,UserInfoID,ChanceTypeID,PLSettingID,IMSI,IMEI,Number,Area,Plmn,Mac,UserAccount ");
            strSql.Append(" FROM [User] ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            return DbHelperSQL.Query(strSql.ToString());
        }


        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetList(int pageIndex, int pageSize, string strWhere = "")
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * from( select u.ID,ci.Name PName,ci.ID Pid,u.IsRobot,u.State,u.RegisterTime,ui.name UserName, u.UserInfoID,u.ChanceTypeID,u.PLSettingID,u.IMSI,u.IMEI,u.Number,u.Area,u.Plmn,u.Mac,u.UserAccount,u.InviteScore,u.InviteTotalScore,u.InviteSuccessNum,u.InviteUserID,u.InviteTime,SUM(o.Price) Price,ROW_NUMBER() OVER(order by u.RegisterTime desc) as RowNumber ");
            strSql.Append(" FROM [User] u left join Communication ci on ci.id=u.CommunicationID left join userinfo ui on u.userinfoid = ui.id left join [Order] o on u.ID = o.UserID  ");
            if (!string.IsNullOrEmpty(strWhere))
                strSql.Append(strWhere);
            strSql.Append(" group by u.ID,ci.Name,ci.ID,u.IsRobot,u.State,u.RegisterTime,ui.name,u.UserInfoID,u.ChanceTypeID,u.PLSettingID,u.IMSI,u.IMEI,u.Number,u.Area,u.Plmn,u.Mac,u.UserAccount,u.InviteScore,u.InviteSuccessNum,u.InviteTotalScore,u.InviteUserID,u.InviteTime) a where  RowNumber BETWEEN " + ((pageIndex - 1) * pageSize + 1) + " and " + pageIndex * pageSize + ";");
            strSql.Append(" select COUNT(1) from [User] u inner join UserInfo ui on u.UserInfoID =ui.ID ");
            if (!string.IsNullOrEmpty(strWhere))
                strSql.Append(strWhere);
            return DbHelperSQL.Query(strSql.ToString());
        }

        /// <summary>
        /// 获得前几行数据
        /// </summary>
        public DataSet GetList(int Top, string strWhere, string filedOrder)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select ");
            if (Top > 0)
            {
                strSql.Append(" top " + Top.ToString());
            }
            strSql.Append(" ID,CommunicationID,IsRobot,State,RegisterTime,UserInfoID,ChanceTypeID,PLSettingID,IMSI ");
            strSql.Append(" FROM [User] ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            strSql.Append(" order by " + filedOrder);
            return DbHelperSQL.Query(strSql.ToString());
        }

        /*
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public DataSet GetList(int PageSize,int PageIndex,string strWhere)
        {
            SqlParameter[] parameters = {
                    new SqlParameter("@tblName", SqlDbType.VarChar, 255),
                    new SqlParameter("@fldName", SqlDbType.VarChar, 255),
                    new SqlParameter("@PageSize", SqlDbType.Int),
                    new SqlParameter("@PageIndex", SqlDbType.Int),
                    new SqlParameter("@IsReCount", SqlDbType.Bit),
                    new SqlParameter("@OrderType", SqlDbType.Bit),
                    new SqlParameter("@strWhere", SqlDbType.VarChar,1000),
                    };
            parameters[0].Value = "[User]";
            parameters[1].Value = "ID";
            parameters[2].Value = PageSize;
            parameters[3].Value = PageIndex;
            parameters[4].Value = 0;
            parameters[5].Value = 0;
            parameters[6].Value = strWhere;	
            return DbHelperSQL.RunProcedure("UP_GetRecordByPage",parameters,"ds");
        }*/

        #endregion  Method
    }
}

